import { operateMgr } from "./operateMgr.js"
import { PwdData, EPwdStatus } from '../datas/PwdData.js';
import { protocol } from '../protocol.js';

export const operateLogin = {
    checkPWD(_password = "0000", is24Hourmodel = false, callback = null) {
        //设置回调
        operateMgr.setCallback(protocol.PWD_COMFIRM, this.onLoginResult);
        this.callback = callback;

        const pwd_bytesArray = this.intToBytes(parseInt(_password, 10));//设置密码
        console.log("密码：", pwd_bytesArray)
        const date = new Date();
        const year1 = this.yearToHex(date.getFullYear()).substring(0, 2);
        const year2 = this.yearToHex(date.getFullYear()).substring(2, 4);
        const hexNumbers = [
            operateMgr.protocolHex(protocol.PWD_COMFIRM),
            '0x' + pwd_bytesArray[3],
            '0x' + pwd_bytesArray[2],
            '0x00',
            '0x' + year1,
            '0x' + year2,
            '0x' + this.monthToHex(date.getMonth() + 1),
            '0x' + this.convertDayToHexString(date.getDate()),
            '0x' + this.hourToHexString(date.getHours()),
            '0x' + this.minuteToHexString(date.getMinutes()),
            '0x' + this.minuteToHexString(date.getSeconds()),
            '0x' + is24Hourmodel ? "1" : "0",
            '0x01'
        ]
        const uint8Array = new Uint8Array(hexNumbers.map(hex => parseInt(hex, 16)));
        operateMgr.characteristic_w.writeValue(uint8Array)
    },

    onLoginResult(cmd, dataView){
        //源码路径：Android_Ble_SDK\android_sdk_source\Demo\VpBluetoothSDK\app\libs\vpprotocol-2.3.04.15.aar\g\k1.class=>(24行).
        //其中第1和2位不知道是什么.没有被使用
        const data = new PwdData();
        data.mStatus = dataView.getUint8(3);
        data.deviceNumber = dataView.getUint16(4);

        data.deviceVersion = dataView.getUint8(6) + "." + dataView.getUint8(7) + "." + dataView.getUint8(8);
        data.deviceTestVersion = data.deviceVersion + "." + dataView.getUint8(9);
        data.isHaveDrinkData = dataView.getUint8(10) == 0 ? false : true;
        data.setisOpenNightTurnWriste(dataView.getUint8(11));
        data.setfindPhoneFunction(dataView.getUint8(18));
        data.setwearDetectFunction(dataView.getUint8(19));
        if (data.mStatus == EPwdStatus.CHECK_FAIL) {
            console.log("密码验证失败.")
        }
        else {
            console.log("密码验证成功.")
        }

        console.log(data.toString());
        if (operateLogin.callback != null) {
            operateLogin.callback(data);
        }
    },

    /***************************/

    intToBytes(_intValue) {
        let var1 = new Uint8Array(4);

        for (let var2 = 0; var2 < 4; var2++) {
            var1[var2] = (_intValue >>> (24 - var2 * 8)) & 0xFF;
        }

        return var1;
    },

    yearToHex(year) {
        if (typeof year !== 'number' || isNaN(year)) {
            throw new Error('Invalid year number');
        }

        // Convert to hexadecimal and pad with leading zeros to 4 digits
        return year.toString(16).toUpperCase().padStart(4, '0');
    },

    monthToHex(month) {
        if (month < 1 || month > 12) {
            throw new Error("Month must be between 1 and 12.");
        }
        // Convert to hex and ensure it's two characters long
        const hexString = month.toString(16).padStart(2, '0');
        return hexString;
    },

    convertDayToHexString(day) {
        // Convert the day to a hexadecimal string
        var hexString = day.toString(16);

        // If the resulting string has only one digit, prepend a '0' to make it two digits
        if (hexString.length === 1) {
            hexString = '0' + hexString;
        }

        return hexString;
    },

    hourToHexString(hour) {
        var hexString = hour.toString(16);
        return hexString.length === 1 ? "0" + hexString : hexString;
    },

    minuteToHexString(minute) {
        var hexString = minute.toString(16);
        return hexString.length === 1 ? "0" + hexString : hexString;
    },
}